
//
//  SpinnerView.swift
//  Automobile
//
//  Created by erkebulan elzhan on 8/10/20.
//  Copyright © 2020 erkebulan elzhan. All rights reserved.
//

import UIKit
import SnapKit

final class SpinnerView: UIActivityIndicatorView {
    
    init() {
        super.init(frame: .zero)
        if #available(iOS 13.0, *) {
            self.style = .medium
        } else {
            self.style = .gray
        }
        
        self.hidesWhenStopped = true
        self.color = .white
        
        
        self.layer.cornerRadius = 12
        self.backgroundColor = UIColor(red: 47/255, green: 130/255, blue: 210/255, alpha: 0.7)
        
        self.snp.makeConstraints { (make) in
            make.width.height.equalTo(60.0)
        }
    }
    
    required init(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

final class RefreshView: UIRefreshControl {
    override init () {
        super.init()
        tintColor = .blueColor
        tintAdjustmentMode = .normal
    }
    
    override func didMoveToWindow() {
        super.didMoveToWindow()
        
       if let l = getNestedSubviews().first(where: { $0.layer is CAReplicatorLayer }), l.subviews.count > 0 {
            l.subviews[0].backgroundColor = .blueColor
        }
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

fileprivate extension UIView {
    class func getNestedSubviews<T: UIView>(view: UIView) -> [T] {
        return view.subviews.flatMap { subView -> [T] in
            var result = getNestedSubviews(view: subView) as [T]
            if let view = subView as? T {
                result.append(view)
            }
            return result
        }
    }

    func getNestedSubviews<T: UIView>() -> [T] {
        return UIView.getNestedSubviews(view: self) as [T]
    }
}
